package cn.b.sky.admin.service.impl;

import cn.b.sky.common.utils.DatabaseUtils;
import cn.b.sky.admin.dao.FactoryDao;
import cn.b.sky.admin.model.BatchJobReport;
import cn.b.sky.admin.model.Factory;
import cn.b.sky.admin.model.condition.FactoryCondition;
import cn.b.sky.admin.service.FactoryService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * 
 * <strong>Title : FactoryServiceImpl.java<br></strong>
 * <strong>Package : cn.b.sky.admin.service.impl<br></strong>
 * <strong>Description : </strong>工厂服务实现类<br> 
 * <strong>Create on : 2016年6月12日 上午11:33:26<br></strong>
 * <p>
 * @author Yantao.Lu<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 * <strong>修改历史:</strong><br>
 * 修改人|修改日期|修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */
@Service
public class FactoryServiceImpl implements FactoryService {

  private static final Logger LOG = LoggerFactory.getLogger(FactoryServiceImpl.class);

  private static final String COLUMN_SITECODE = "SITECODE";

  private static final String COLUMN_TENANTID = "TENANTID";

  @Autowired
  FactoryDao factoryDao;

  @Override
  public List<Factory> selectAllFactories() {
    return factoryDao.selectAllFactories();
  }

  @Override
  public List<Factory> selectFactoryListByCondition(FactoryCondition condition) {
    return factoryDao.selectFactoryListByCondition(condition);
  }

  @Override
  public int selectFactoryCountByCondition(FactoryCondition condition) {
    return factoryDao.selectFactoryCountByCondition(condition);
  }

  @Override
  public void insertFactory(Factory factory) {
    factoryDao.insertFactory(factory);
  }

  @Override
  public void updateFactory(Factory factory) {
    factoryDao.updateFactory(factory);
  }

  @Override
  public Factory selectFactory(String siteCode) {
    return factoryDao.selectFactory(siteCode);
  }

  @Override
  public BatchJobReport deleteFactory(String siteCode, Set<String> tableSet) {
    if (StringUtils.isBlank(siteCode)) {
      return new BatchJobReport("", "", "siteCode 为空", false);
    }
    boolean success = true;
    String cause = "";
    try {
      if (!tableSet.isEmpty()) {
        Object[] tableNames = tableSet.toArray();
        for (int i = tableNames.length - 1; i >= 0; i--) {
          Set<String> columnSet = factoryDao.getTableColumns(tableNames[i].toString());
          if (!columnSet.isEmpty()) {
            if (columnSet.contains(COLUMN_SITECODE)) {
              factoryDao.deleteFactoryData(tableNames[i].toString(), COLUMN_SITECODE, siteCode);
            } else if (columnSet.contains(COLUMN_TENANTID)) {
              factoryDao.deleteFactoryData(tableNames[i].toString(), COLUMN_TENANTID, siteCode);
            }
          }
        }
      }
      factoryDao.deleteFactory(siteCode);
    } catch (Exception e) {
      LOG.error("{}", e);
      success = false;
      String errorMsg = e.getMessage();
      if (DatabaseUtils.isConstraintsError(e.getMessage())) {
        //外键删除已存在提示
        errorMsg = "已经为该工厂创建数据，不能删除！";
      }
      cause = errorMsg;
    }
    return new BatchJobReport(siteCode, "删除失败", cause, success);
  }

  @Override
  public void insertTableData(String tableName, String sourceSiteCode, String targetSiteCode) {
    copyTableDataFromSource(tableName, sourceSiteCode, targetSiteCode);
  }

  @Override
  public void insertTableData(Factory factory, Set<String> tableSet, String sourceSiteCode) {
    if (null != selectFactory(factory.getSiteCode())) {
      updateFactory(factory);
    } else {
      insertFactory(factory);
    }
    for (String tableName : tableSet) {
      if (tableName.equalsIgnoreCase("SY_SITE")) {
        continue;
      }
      copyTableDataFromSource(tableName, sourceSiteCode, factory.getSiteCode());
    }

  }

  private void copyTableDataFromSource(String tableName, String sourceSiteCode, String targetSiteCode) {
    Set<String> columnSet = factoryDao.getTableColumns(tableName);
    if (!columnSet.isEmpty()) {
      if (columnSet.contains(COLUMN_SITECODE)) {
        factoryDao.insertFactoryData(tableName, COLUMN_SITECODE, columnSet, sourceSiteCode, targetSiteCode);
      } else if (columnSet.contains(COLUMN_TENANTID)) {
        factoryDao.insertFactoryData(tableName, COLUMN_TENANTID, columnSet, sourceSiteCode, targetSiteCode);
      }
    }
  }

  @Override
  public void updateAdminPassword(String siteCode, String password) {
    factoryDao.updateAdminPassword(siteCode, password);
  }

}
